using System;
using System.Collections.Generic;
using System.Text;

using Castle.Core.Logging;
using Castle.Core.Interceptor;
using Castle.Facilities.PolicyInjection;

namespace TestConsole.Policies.Handlers
{
    public class LogHandler
    {
        private ILogger m_Logger = NullLogger.Instance;

        public ILogger Logger
        {
            get
            {
                return m_Logger;
            }
            set
            {
                m_Logger = value;
            }
        }

        private DateTime m_CreationTime;

        public DateTime CreationTime
        {
            get
            {
                return m_CreationTime;
            }
        }

        public LogHandler()
        {
            m_CreationTime = DateTime.Now;
        }

        public HandlerPrecallResult PreCall(HandlerContext handlerContext)
        {
            Console.Out.WriteLine("--- LogHandler PreCall ---");
            Console.Out.WriteLine("Method {0}", handlerContext.Invocation.Method.Name);
            m_Logger.Info("PreCall Method {0}", handlerContext.Invocation.Method.Name);
            return HandlerPrecallResult.Continue;
        }

        public void PostCall(HandlerContext handlerContext)
        {
            Console.Out.WriteLine("--- LogHandler PostCall ---");
            Console.Out.WriteLine("Method {0}", handlerContext.Invocation.Method.Name);
            m_Logger.Info("PostCall Method {0}", handlerContext.Invocation.Method.Name);
            if (handlerContext.Invocation.Method.ReturnType != typeof(void))
            {
                Console.Out.WriteLine("Return value: {0}", handlerContext.Invocation.ReturnValue.ToString());
            }            
        }

        public void OnException(HandlerContext handlerContext, Exception ex)
        {
            Console.Out.WriteLine("--- LogHandler OnException ---");
            Console.Out.WriteLine("Method {0}", handlerContext.Invocation.Method.Name);
            m_Logger.Error("Exception Method {0}", handlerContext.Invocation.Method.Name, ex);
        }
    }
}
